/**
 * Copyright 2011 Honeywell Federal Manufacturing & Technologies, LLC. This material was produced under U.S. Government
 * contract DE-ACO4-01AL66850, Honeywell Federal Manufacturing & Technologies, LLC, (FM&T) with the U. S. Department of
 * Energy for the operation of the Kansas City Plant . The U.S. Government has rights to use, reproduce, and distribute
 * this software.  NEITHER THE GOVERNMENT NOR Honeywell Federal Manufacturing & Technologies, LLC, MAKES ANY WARRANTY,
 * EXPRESS OR IMPLIED, OR ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE.  If software is modified to produce
 * derivative works, such modified software should be clearly marked, so as not to confuse it with the version available
 * from FM&T.
 *
 * Additionally, this program is free software; you can redistribute it and/or modify it under the terms of the GNU
 * General Public License Version 3 published by the Free Software Foundation. Accordingly, this program is distributed in
 * the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with this library.
 * If not, see http://www.gnu.org/licenses/.
 */
package org.braintrain.tapestry.services;

import com.kcp.ko.fmtnmlib.service.HibernatePersistenceService;
import org.apache.tapestry.IRequestCycle;
import org.apache.tapestry.engine.IEngineService;
import org.apache.tapestry.engine.ILink;
import org.apache.tapestry.engine.state.ApplicationStateManager;
import org.apache.tapestry.services.DataSqueezer;
import org.apache.tapestry.services.LinkFactory;
import org.apache.tapestry.util.ContentType;
import org.apache.tapestry.web.WebResponse;
import org.braintrain.domain.Content;
import org.braintrain.domain.Navigation;
import org.braintrain.domain.types.BrainTrainRole;
import org.braintrain.services.DeltaResourceManager;
import org.braintrain.tapestry.aso.Visit;

import javax.activation.MimetypesFileTypeMap;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;


/**
 * The Tapestry Service used to produce the "rollover" or "popup" effect
 * 
 * @author John Ericksen
 *
 */
public class ContentViewService implements IEngineService{
    
    public static final String SERVICE_NAME = "contentViewService";
    
    private LinkFactory linkFactory;
    
    private HibernatePersistenceService genericHibernateService;
    
    private DataSqueezer dataSqueezer;

    private DeltaResourceManager resourceManager;

    private MimetypesFileTypeMap mimeTypes = new MimetypesFileTypeMap();
    
    public static final String NAVIGATION_ID = "navigationId";
    
    private ApplicationStateManager appStateManager;
    
    public void service(IRequestCycle cycle) throws IOException {
        WebResponse response = cycle.getInfrastructure().getResponse();
            
        Long navigationId = (Long)dataSqueezer.unsqueeze(cycle.getParameter(NAVIGATION_ID));

        Navigation navigation = genericHibernateService.getById(Navigation.class, navigationId);

        OutputStream out = response.getOutputStream(new ContentType(mimeTypes.getContentType("txt.html")));

        if(getBraintrainVisit() != null && getBraintrainVisit().getUser() != null)
        {

            boolean deltaUser = BrainTrainRole.checkRoles(getBraintrainVisit().getAuthenticatedUser(),
                    new BrainTrainRole[] {BrainTrainRole.contentcreator, BrainTrainRole.cmstaff});

            Content content = (Content)navigation.getContent(deltaUser);

            //Caching on the browser... speeds up regular user's viewing
            if(deltaUser)
            {
                response.setHeader("Cache-Control", "max-age=0");
            }
            else
            {
                response.setHeader("Cache-Control", "max-age=3600");
            }



            if(content != null)
            {
                resourceManager.getResourceValue(out, content.getContent());
            }
            else
            {
                response.setHeader("Cache-Control", "max-age=0");
                out.write("No Data".getBytes());
            }
        }
        else
        {
            response.setHeader("Cache-Control", "max-age=0");
            out.write("No Data".getBytes());
        }
        out.flush();
        out.close();
    }
    
    public ILink getLink(boolean post, Object parameter) {
        /*if(parameter instanceof Object[] && ((Object[])parameter).length > 0)
        {
            parameter = ((Object[])parameter)[0];
        }*/
        Map<String, String> parameters = new HashMap<String, String>();
        parameters.put(NAVIGATION_ID, dataSqueezer.squeeze(parameter));
        return linkFactory.constructLink(this, post, parameters, false);
    }

    public String getName() {
        return SERVICE_NAME;
    }
    
    public ApplicationStateManager getAppStateManager() {
        return appStateManager;
    }
    
    public void setAppStateManager(ApplicationStateManager appStateManager) {
            this.appStateManager = appStateManager;
    }
    
    public Visit getBraintrainVisit()
    {
        return (Visit)getAppStateManager().get("visit");
    }

    public void setLinkFactory(LinkFactory linkFactory) {
        this.linkFactory = linkFactory;
    }
    
    public void setGenericService(HibernatePersistenceService genericService) {
        this.genericHibernateService = genericService;
    }

    public void setDataSqueezer(DataSqueezer dataSqueezer) {
        this.dataSqueezer = dataSqueezer;
    }

    public void setResourceManager(DeltaResourceManager resourceManager) {
        this.resourceManager = resourceManager;
    }
}
